#!/bin/sh
#
# rm-all -- remove all docker labs
#
# Copyright (C) 2016-2021 Wu Zhangjin <falcon@ruma.tech>
#

if [ -z "$RELEASE" ]; then
  export RELEASE=0
else
  LOCAL_RELEASE=$RELEASE
fi

TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd)"
. "$TOP_DIR"/tools/docker/config >/dev/null

log_print "Get all of containers"
id_names=`docker ps --format='{{.ID}},{{.Names}}' -a -q`

for id_name in $id_names
do
    id=$(echo $id_name | cut -d ',' -f1)
    name=$(echo $id_name | cut -d ',' -f2)

    if [ "$name" = "$WPROXY_NAME" -o "$name" = "$TPROXY_NAME" ]; then
        info_print "Remove $name ..."
        docker rm -f $name

        info_print "Disconnect $name from cloud-lab-net"
        docker network disconnect -f cloud-lab-net $name 2>/dev/null
        continue
    fi

    lab=`echo $name | sed -e "s%-[0-9]*-[0-9a-zA-Z]\{6,6\}$%%g"`
    get_labs | tr ' ' '\n' | grep -q ^$lab$
    [ $? -ne 0 ] && continue

    info_print "Remove $lab ..."
    docker rm -f $name

    info_print "Disconnect $name from cloud-lab-net"
    docker network disconnect -f cloud-lab-net $name 2>/dev/null
done

log_print "Remove cloud-lab-net"
docker network rm cloud-lab-net

[ -z "$id_names" ] && info_print "No running or exited containers found." && exit 0

if [ "x$LOCAL_RELEASE" != "x0" ]; then
  log_print "Update release page"
  "$DOCKER_RELEASE_CMD" all >/dev/null 2>&1 &
fi
